package com.taocore.top.title.service;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.commons.lang.StringUtils;

import com.taobao.api.domain.ItemProp;
import com.taobao.api.domain.PropValue;
import com.taobao.api.response.ItempropsGetResponse;
import com.taocore.top.title.domain.DiagnoseResult;

public class BrandsChecker implements TitleChecker{

	static Logger _log = Logger.getLogger(BrandsChecker.class.getName());
	
	public static final int BRANDS_MAX = 1;
	
	private long cid;
	
	public BrandsChecker(long cid)
	{
		this.cid = cid;
	}
	
	@Override
	public DiagnoseResult check(String title) {
		List<String> brands = new ArrayList<String>();
		TaobaoService service = new TaobaoService();
		try
		{
			ItempropsGetResponse rsp = service.getBrandsProps(cid);
			_log.info("cid: " + cid);
			if (rsp.isSuccess())
			{
				List<ItemProp> props = rsp.getItemProps();
				if (props != null && !props.isEmpty())
				{
					ItemProp prop = props.get(0);
					List<PropValue> propValues = prop.getPropValues();
					//todo: get category brands and use cache to reduce api call
					if (propValues != null)
					{
						for (PropValue propValue : propValues)
						{
							String name = propValue.getName();
							String[] tokens = StringUtils.split(name, '/');
							String brand = checkBrandValue(title, tokens);
							if (brand != null && !brands.contains(brand))
							{
								brands.add(brand);
							}
						}
					}
				}
			}
			else
			{
				_log.warning(TaobaoService.getError(rsp));
			}
		}
		catch (Exception e) {
			_log.log(Level.SEVERE, "", e);
		}
		
		if (brands.size() > 1)
		{
			DiagnoseResult result = new DiagnoseResult();
			result.setMsg("标题出现品牌堆砌：" + brands + "。 品牌词超过两个，会降权，超过5个，视为违规商品，权重降为0。");
			return result;
		}
		return null;
	}

	private String checkBrandValue(String title, String[] tokens)
	{
		if (title != null && tokens != null)
		{
			for (String token : tokens)
			{
				if (StringUtils.containsIgnoreCase(title, token))
				{
					return token;
				}
			}
		}
		return null;
	}
}
